package com.hnas.trade.dao.impl;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.hnas.activity.domain.ActivityType;
import com.hnas.core.app_common.util.DateUtil;
import com.hnas.core.dao.BaseDaoImpl;
import com.hnas.core.util.StringUtil;
import com.hnas.trade.dao.OrderDao;
import com.hnas.trade.domain.OrderStatus;
import com.hnas.trade.domain.OrderType;
import com.hnas.trade.dto.DTOOrder;
import com.hnas.trade.mapper.OrderMapper;
import com.hnas.trade.orm.Order;

@Component("orderDao")
public class OrderDaoImpl extends BaseDaoImpl<Order> implements OrderDao{
	
	@Value("#{component['east_square_mrch_id']}")//最低消费
	private String eastSquareMrchId = "1111111111";

	public OrderDaoImpl() {
		super(Order.class);
	}

	@Override
	public Order saveOrUpdate(DTOOrder dto){
		Order vo = null;
		try {
			if(dto != null){
				String id = dto.getId();
				if(StringUtil.isNotEmpty(id)){
					vo = this.find(id);
				}	
				if(vo == null){//新增
					vo = new Order();
					BeanUtils.copyProperties(dto, vo);
					this.persist(vo);
				}else{//修改
					BeanUtils.copyProperties(dto, vo, new String[]{"createTime","creator"});
					this.merge(vo);
				}
			}
			return vo;
		} catch (Exception e) {
			e.printStackTrace();
			return vo;
		}
	}
	
	@Override
	public Order saveOrUpdate2(DTOOrder dto) throws Exception{
		Order vo = null;
		if(dto != null){
			String id = dto.getId();
			if(StringUtil.isNotEmpty(id)){
				vo = this.find(id);
			}	
			if(vo == null){//新增
				vo = new Order();
				BeanUtils.copyProperties(dto, vo);
				this.persist(vo);
			}else{//修改
				BeanUtils.copyProperties(dto, vo, new String[]{"createTime","creator"});
				this.merge(vo);
			}
		}
		return vo;
	}

	@Override
	public DTOOrder getByOrderNo(String order_no) {
		String hql = "from Order t where t.orderNo = ?1 ";
		Query query = this.entityManager.createQuery(hql,Order.class);
		query.setParameter(1, order_no);
		List<Order> list =  query.getResultList();
		if(null!=list&&list.size()>0){
			Order vo = list.get(0);
			return OrderMapper.getInstance().mapToValue(vo);
		}
		return null;
	}
	
	@Override
	public Order findByQRCode(String qrCode) {
		List<Order> list = this.findByQuery("from Order t where t.qrcodeNo = ?1", qrCode);
		if(null!=list&&list.size()>0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public void updateOrderStatus(String orderNo, String status) {
		String sql = "update m_base_wxxnk_order set order_status='"+status+"' ,update_time='"+DateUtil.dateTimeToString(new Date())+"' where order_no='"+orderNo+"'";
		Query query = this.getEntityManager().createNativeQuery(sql);
		query.executeUpdate();
		
	}
	
	@Override
	public DTOOrder getBySwiftNumber(String swiftNumber) {
		String hql = "from Order t where t.swiftNumber = ?1";
		Query query = this.entityManager.createQuery(hql,Order.class);
		query.setParameter(1, swiftNumber);
		Order order = (Order) query.getSingleResult();
		return OrderMapper.getInstance().mapToValue(order);
	}

	@Override
	public List<Order> getTodaySuccessOrder() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String today = simpleDateFormat.format(new Date());
		String begin = today+" 00:00:00";
		String end = today+" 23:59:59";
		String sql = "select *  from m_base_wxxnk_order where order_status='"+OrderStatus.Payed.getStatus()+"' and create_time BETWEEN STR_TO_DATE('"+begin+"','%Y-%m-%d %H:%i:%s') and STR_TO_DATE('"+end+"','%Y-%m-%d %H:%i:%s')";
		System.out.println("today Sql:"+sql);
		Query query = this.entityManager.createNativeQuery(sql,Order.class);
		List<Order> list = query.getResultList();
		return list;
	}

	@Override
	public List<Order> getEastSquarList(String date) {
		String hql = "from Order t where t.mrchId = '"+eastSquareMrchId+"' and t.createTime >= ?1 and t.isDeleted = false";
		return this.findByQuery(hql, date);
	}

	@Override
	public int getEastSquarCount(String date) {
//		String sql = "select count(id) from m_base_wxxnk_order t where t.mrch_id = '"+eastSquareMrchId+"' and t.create_time >= ?1 and t.order_status in ('0','1') and t.is_deleted = false and t.id is not null";
		String sql = "select count(t.id) from m_base_wxxnk_order t left join m_base_wxxnk_order_detail t2 on t.order_no = t2.order_no where t.create_time >= ?1 and t.order_status in ('0','1') and t.is_deleted = false and t.id is not null and t2.activity_item_type = '"+ActivityType.SJJ.getType()+"'";
		Query query = this.entityManager.createNativeQuery(sql);
		query.setParameter(1, date);
		return ((BigInteger)query.getSingleResult()).intValue();
	}

	@Override
	public int getCountByActivity(String mrchId, String termNo, String id, String dateStr) {
		String sql = "select count(distinct(t1.id)) from m_base_wxxnk_order t1 left join m_base_wxxnk_order_detail t2 on t1.order_no = t2.order_no where t1.mrch_id = ?1 and t1.term_no = ?2 and t2.activity_id = ?3 and LEFT(t1.create_time,10) >= ?4 and t1.order_status in ('0','1') and t1.is_deleted = false and t.id is not null ";
		Query query = this.entityManager.createNativeQuery(sql);
		query.setParameter(1, mrchId);
		query.setParameter(2, termNo);
		query.setParameter(3, id);
		query.setParameter(4, dateStr);
		return ((BigInteger)query.getSingleResult()).intValue();
	}

	@Override
	public int getCountByAccno(String accno, String activityId,String itemId, String dateStr) {
		if(StringUtil.isEmpty(accno)) return 0;
		String sql = "select count(distinct(t1.id)) from m_base_wxxnk_order t1 left join m_base_wxxnk_order_detail t2 on t1.order_no = t2.order_no where t1.acc_no = ?1 and t1.activity_id = ?2 and t2.relate_id = ?3 and t1.order_status in ('0','1') and t1.is_deleted = false and t1.id is not null ";
		Query query = this.entityManager.createNativeQuery(sql);
		query.setParameter(1, accno);
		query.setParameter(2, activityId);
		query.setParameter(3, itemId);
//		query.setParameter(4, dateStr);
		return ((BigInteger)query.getSingleResult()).intValue();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DTOOrder> listAccountOrder(String accId, String cardNo) {
		String hql = "from Order t where t.applicationType = '04' and t.orderStatus = '7' and t.accId = ?1 and t.cardNo = ?2";
		Query query = this.entityManager.createQuery(hql,Order.class);
		query.setParameter(1, accId);
		query.setParameter(2, cardNo);
		List<Order> resultList = query.getResultList();
		if(resultList == null) return null;
		if(resultList.size() <= 0) return new ArrayList<DTOOrder>();
		return OrderMapper.getInstance().mapToValue(resultList);
	}

	@Override
	public int getOrderCountByCardNo(String cardNo) {
		if(StringUtil.isEmpty(cardNo)) return 0;
		String sql = "select count(1) from m_base_wxxnk_order t where t.order_type <> '" + OrderType.DZKGK.getType() + "' and t.card_no = ?1";
		Query query = this.entityManager.createNativeQuery(sql);
		query.setParameter(1, cardNo);
		return ((BigInteger)query.getSingleResult()).intValue();
	}
	
}
